package com.qing.common.util

import android.content.Context
import android.util.Log
import java.io.File

object FileUtils {

    const val TAG = "FileUtils"

    private const val DEFAULT_LOG_DIR = "log"

    private const val DEFAULT_LOG_FILE_NAME = "log.gz"

    fun getDefaultCacheLogFile(context: Context): File {
        return File(getLogCacheDir(context), DEFAULT_LOG_FILE_NAME).apply {
            Log.i(TAG, "getLogFile: path=$path")
            if (!exists()) createNewFile()
        }
    }

    fun getExternalLogFile(context: Context): File {
        val logFolder = File(context.externalCacheDir, DEFAULT_LOG_DIR)
        if (!logFolder.exists()) {
            logFolder.mkdirs()
        }
        val file = File(logFolder, DEFAULT_LOG_FILE_NAME).apply {
            Log.i(TAG, "getLogFile: path=$path")
            if (!exists()) createNewFile()
        }
        return file
    }

    fun getLogFile(path: String): File {
        val file = File(path)
        if (file.parentFile?.exists() == false) {
            file.parentFile?.mkdirs()
        }
        if (!file.exists()) file.createNewFile()
        return file
    }

    fun isFileExists(path: String): Boolean {
        return File(path).exists()
    }

    fun deleteFile(path: String) {
        val file = File(path)
        if (file.exists()) {
            if (file.isDirectory) {
                file.listFiles()?.forEach {
                    deleteFile(it.absolutePath)
                }
            } else {
                file.delete()
            }
        }
    }

    fun copyFile(src: String, dst: String) {
        val srcFile = File(src)
        val dstFile = File(dst)
        if (srcFile.exists()) {
            if (srcFile.isDirectory) {
                dstFile.mkdirs()
                srcFile.listFiles()?.forEach {
                    copyFile(it.absolutePath, "${dstFile.absolutePath}${File.separator}${it.name}")
                }
            } else {
                srcFile.copyTo(dstFile, true)
            }
        }
    }

    /**
     * 创建文件
     *
     * 如果文件不存在，则创建文件，如果文件存在，则删除后创建
     */
    fun createFile(path: String): File {
        val file = File(path)
        if (file.parentFile?.exists() == false) {
            file.parentFile?.mkdirs()
        }
        if (file.exists()) file.delete()
        file.createNewFile()
        return file
    }

    fun getCacheWavPath(context: Context): String {
        return "${context.externalCacheDir!!.absolutePath}${File.separator}wav${File.separator}temp.wav"
    }

    private fun getLogCacheDir(context: Context): File {
        return File(context.cacheDir, DEFAULT_LOG_DIR).apply {
            if (isFile) {
                delete()
                mkdirs()
                return@apply
            }
            if (!exists()) mkdirs()
        }
    }

}